package me.send.business.base.oss;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.media.MediaConfiguration;
import com.alibaba.media.Result;
import com.alibaba.media.client.MediaClient;
import com.alibaba.media.client.impl.DefaultMediaClient;
import com.alibaba.media.upload.UploadPolicy;
import com.alibaba.media.upload.UploadRequest;
import com.alibaba.media.upload.UploadResponse;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 该示例代码展示了如果在OSS中创建和删除一个Bucket，以及如何上传和下载一个文件。
 * 
 * 该示例代码的执行过程是： 1. 创建一个Bucket（如果已经存在，则忽略错误码）； 2. 上传一个文件到OSS； 3. 下载这个文件到本地； 4.
 * 清理测试资源：删除Bucket及其中的所有Objects。
 * 
 * 尝试运行这段示例代码时需要注意： 1. 为了展示在删除Bucket时除了需要删除其中的Objects,
 * 示例代码最后为删除掉指定的Bucket，因为不要使用您的已经有资源的Bucket进行测试！ 2.
 * 请使用您的API授权密钥填充ACCESS_ID和ACCESS_KEY常量； 3.
 * 需要准确上传用的测试文件，并修改常量uploadFilePath为测试文件的路径； 修改常量downloadFilePath为下载文件的路径。 4.
 * 该程序仅为示例代码，仅供参考，并不能保证足够健壮。
 *
 */
public class OSSObjectSample {

	private static final String ACCESS_ID = "uPM5zGYwUodcy9eI";
	private static final String ACCESS_KEY = "FZWeZLT9AS5Kol4FAcjTCdQWd5ksWC";

	private static final String BUCKET_NAME = "produce-send";
	
	private static final String NAMESPACE = "static";
	

	private static OSSClient client = null;

	@SuppressWarnings("deprecation")
	private static void initialize() {
		if (client == null) {
			client = new OSSClient(ACCESS_ID, ACCESS_KEY);
		}
	}

	
	/**********************************玩兔配置***************************************/
	public static String putFile(String key, File file, String serviceName){
		MediaConfiguration conf = new MediaConfiguration();
		conf.setType(MediaConfiguration.TYPE_TOP);
		conf.setAk("23205578");
		conf.setSk("302f6ae42b0a40f85e75abfe3b58896a");
		conf.setNamespace(NAMESPACE);
		 
		// 0.2 获取Client
		MediaClient mediaClient = new DefaultMediaClient(conf);
		 
		// 0.3 待上传的文件
		 
		// 0.4 自定义上传策略
		UploadPolicy uploadPolicy = new UploadPolicy();
		uploadPolicy.setInsertOnly(UploadPolicy.INSERT_ONLY_NONE);
		uploadPolicy.setExpiration(System.currentTimeMillis() + 3600 * 1000);
		 
		 
		UploadRequest uploadRequest = new UploadRequest(uploadPolicy);
		uploadRequest.setFile(file);
		uploadRequest.setDir(serviceName);
		uploadRequest.setName(key);
		Result<UploadResponse> result = mediaClient.upload(uploadRequest);
		System.out.println("cdode:"+result.getCode()+",httpstatus:"+result.getHttpStatus()+",message:"+result.getMessage());
		System.out.println("上传文件的路径："+result.getData().getUrl());
		
		String path = "";
		if (result.getHttpStatus()==200) {
			path = result.getData().getUrl();
		}
		
		return path;
	} 
	/**********************************玩兔配置***************************************/
	
	
	/**
	 * 
	 * 上传文件 2015年7月2日14:11:27
	 * 
	 * @param key
	 *            服务器的文件名称
	 * 
	 * @param file
	 *            要上传的文件
	 * 
	 * @param serviceName
	 *            那个服务器要访问的路径
	 * @return
	 * @throws OSSException
	 * @throws ClientException
	 * @throws FileNotFoundException
	 */
	public static String OSSPutObject(String key, File file, String serviceName) {
		initialize();
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		// 可以在metadata中标记文件类型
//		objectMeta.setContentType("image/jpeg");
		InputStream input;
		try {
			input = new FileInputStream(file);
			client.putObject(BUCKET_NAME, serviceName + "/" + key, input,
					objectMeta);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return "http://" + BUCKET_NAME + ".oss-cn-hangzhou.aliyuncs.com/"
				+ serviceName + "/" + key;
	}

	
	public static String OSSPutObject(String key,MultipartFile multipartFile , String serviceName) {
		initialize();
		
		CommonsMultipartFile commonsMultipartFile= (CommonsMultipartFile)multipartFile; 
        DiskFileItem diskFileItem = (DiskFileItem)commonsMultipartFile.getFileItem(); 
        File file = diskFileItem.getStoreLocation();
        if (file!=null) {
			System.out.println("file is not null");
			System.out.println("name is :"+file.getName());
		}else {
			System.out.println("file is null");
		}
        return putFile(key, file, serviceName);
//        return OSSPutObject(key, file, serviceName);
	}
	
}
